package com.hunantv.mglive.service;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.advert.AdvertModel;
import com.hunantv.mglive.data.advert.AdvertRequestModel;
import com.hunantv.mglive.utils.AdvertHandle;
import com.hunantv.mglive.utils.AdvertPreference;
import com.hunantv.mglive.utils.DeviceInfoUtil;
import com.hunantv.mglive.utils.FileUtils;
import com.hunantv.mglive.utils.HttpUtils;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.StringUtil;

import org.json.JSONException;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2016/2/19.
 */
public class AdvertService extends Service implements HttpUtils.callBack {
    private static final String TAG = "AdvertService";
    private HttpUtils mHttp;

    public AdvertService() {
        mHttp = new HttpUtils(this, this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        L.d(TAG, "广告后台服务启动");
        requestAdvert();
    }

    private long l;

    private void requestAdvert() {
        l = System.currentTimeMillis();
        String requestJson = getRequestJson();
        L.d(TAG, requestJson);
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("p", requestJson)
                .build();
        post(BuildConfig.URL_APP_START_ADVERT, body);

    }

    /**
     * 构造请求参数
     *
     * @return
     */
    private String getRequestJson() {
        AdvertRequestModel model = new AdvertRequestModel();
        model._v = "1";
        //页面相关
        model.m.p = 4880;
        model.m.aid = 198;
        model.m.init = 0;
        //用户相关
        model.u.id = 816617603;
        //设备相关
        if (DeviceInfoUtil.isTablet(this)) {
            model.c.type = 32;//安卓平板
        } else {
            model.c.type = 33;//安卓手机
        }
        model.c.os = "android " + Build.VERSION.RELEASE;//系统版本
        model.c.version = DeviceInfoUtil.getVersionName(this);//app版本
        model.c.brand = Build.BRAND;//设备品牌
        model.c.operator = DeviceInfoUtil.getSimOperatorInfo(this);//运营商信息，00 移动 01 联通 03 电信 04 互联网电视(对应原始值 00)
        model.c.mcc = DeviceInfoUtil.getSimCountryMCC(this);// 相关运营商国家码
        model.c.mn = Build.MODEL;// * 设备型号
        model.c.rs = DeviceInfoUtil.getResolution2(this);// 分辨率
        model.c.lt = 1;// 横竖屏状态 0:未知 1:竖屏 2:横屏
        model.c.idfa = "";// * iOS设备身份码
        model.c.net = DeviceInfoUtil.getNetWork(this);//上网方式 0 wifi, 1 mobile, 2 no network
//        model.c.openudid = "";//https://github.com/ylechelle/OpenUDID
        model.c.aaid = DeviceInfoUtil.getDeviceId(this);
        model.c.ts = System.currentTimeMillis() / 1000;//* 发送请求的时间点 取当前Unix时间戳
        return JSON.toJSONString(model);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public boolean get(String url, Map<String, String> param) {
        return mHttp.get(url, param);
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return mHttp.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {
        if (BuildConfig.URL_APP_START_ADVERT.equals(url)) {
            stopSelf();
        }
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException, RemoteException {
        if (BuildConfig.URL_APP_START_ADVERT.equals(url)) {
            stopSelf();
        }
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.URL_APP_START_ADVERT.equals(url)) {
            //异步线程中下载图片
            AdvertModel advertModel = JSON.parseObject(resultModel.getData(), AdvertModel.class);
            AdvertHandle.getInstance().setAdvert(advertModel);
            L.d(TAG, "时间=" + (System.currentTimeMillis() - l));
            String advertUrl = advertModel.getUrl();
            saveNetImg(advertUrl);
            List<String> advertUrls = advertModel.getBackup_url();
            if (advertUrls == null) {
                return null;
            }
            for (int i = 0; i < advertUrls.size(); i++) {
                String item = advertUrls.get(i);
                saveNetImg(item);
            }
        }
        return null;
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        if (BuildConfig.URL_APP_START_ADVERT.equals(url)) {
            stopSelf();
        }
    }

    public void saveNetImg(final String url) {
        try {
            if (!StringUtil.isNullorEmpty(url) && !AdvertPreference.getInstance(this).isSave(url)) {
                //没有缓存过
                L.d(TAG, "广告下载开始,URL=" + url);
                File cacheFile = Glide.with(MaxApplication.getAppContext())
                        .load(url)
                        .downloadOnly(DeviceInfoUtil.getResolutionWidth(MaxApplication.getAppContext()), DeviceInfoUtil.getResolutionHeight(MaxApplication.getAppContext()))
                        .get();
                byte[] data = FileUtils.toByteArray(cacheFile);
                L.d(TAG, "广告下载成功,URL=" + url + "   size=" + data.length);
                AdvertPreference.getInstance(this).saveAdvert(url, data);
                L.d(TAG, "广告缓存成功,URL=" + url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
